package com.shk.controller;


import com.alibaba.dubbo.config.annotation.Reference;
import com.shk.annotation.Log4jAnnotation;
import com.shk.constant.MessageConstant;
import com.shk.entity.PageResult;
import com.shk.entity.QueryPageBean;
import com.shk.entity.Result;
import com.shk.pojo.User;
import com.shk.service.RoleService;
import com.shk.service.UserService;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.sql.ResultSet;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.logging.SimpleFormatter;

@RestController
@RequestMapping("/user")
public class UserController {

    @Reference
    private UserService userService;

    @RequestMapping("/findusername")
    private Result findUserName(){
        /*获取框架给我们提供的上下文对象
        * 从对象中获取用户的信息*/
        UserDetails user = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if(user != null){
            String username = user.getUsername();
            System.out.println(username);
            return new Result(true, MessageConstant.GET_USERNAME_SUCCESS,username);
        }
        return new Result(false, MessageConstant.GET_USERNAME_FAIL);

    }
        @RequestMapping("/add")
        @Log4jAnnotation
        public Result add(@RequestBody User user, Integer[] roleIds){
        userService.add(user,roleIds);
        return new Result(true,MessageConstant.ADD_USER_SUCCESS);
        }

    @RequestMapping("/findPage")
    @Log4jAnnotation
    public PageResult findPage(@RequestBody QueryPageBean queryPageBean) throws Exception{
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();
       PageResult page = userService.findPage(currentPage,pageSize,queryString);
        return page;

    }

    @RequestMapping("/delete")
    @Log4jAnnotation
    public Result delete(Integer id){
        userService.delete(id);
        return new Result(true,MessageConstant.DELETE_USER_sUCCESS);
    }

    @RequestMapping("/edit")
    @Log4jAnnotation
    public Result update(@RequestBody User user,Integer[] roleIds){
        userService.update(user,roleIds);
        return new Result(true,MessageConstant.EDIT_USER_SUCCESS);
    }

    @RequestMapping("/findRoleIdsByUserId")
    @Log4jAnnotation
    public Map findRoleIdsByUserId(Integer userId){
      Map map=  userService.findRoleIdsByUserId(userId);
      return map;
    }

}
